// miniprogram/pages/word/wordRemember/wordRemember.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    wordId: null,
    total: null, //总进度
    current: null, //目前进度
    title: "释义测试", //标题
    replied: false, //是否回答
    replyIndex: null, //具体回答的选择
    progress: "", //进度条"61.8%"
    question: "", //问题
    key: "", //答案
    word: {},
    options: [
      // "遇见",
      // "画,图画",
      // "脸",
      // "听,问",
    ]
  },
  /**
   * 把当前页单词加入错题本
   */
  addMistake(word_id) {
    const thiz = this
    wx.cloud.callFunction({
      // 要调用的云函数名称
      name: 'addWrong',
      // 传递给云函数的参数
      data: {
        word_id: word_id
      },
      success: res => {
        // output: res.result === 3
        if (res.result.msg == 'add') {
          console.log("添加错题成功")
        } else if (res.result.msg == 'update') {
          console.log("添加失败,已经在错题本中")
        } else {
          console.log("调用云函数成功，返回值未知")
        }
      },
      fail: err => {
        // handle error
        console.log("调用云函数失败")
      }
    })
  },


  /**
   * 点击回答，让所有不可再点击。
   * 如果回答正确，延迟后，进入下一个页面
   * 如果回答错误，添加到错题本，延迟后，再进入到下一个页面
   * 回答最后一个进入结算界面
   */
  answer(e) {
    console.log("answer's tap event", e)
    const thiz = this
    const option = e.currentTarget.dataset.item
    const index = e.currentTarget.dataset.index
    if (thiz.data.replied) { //回答后，按钮无效化
      return
    }
    this.setData({
      replied: true,
      replyIndex: index
    })
    if (option != this.data.key) {
      console.log("option", option)
      console.log("this.data.key", this.data.key)
      this.addMistake(this.data.wordId)
    }

    //延迟后，更新本页数据
    setTimeout(function() {
      let total = wx.getStorageSync("batch")
      let current = thiz.data.current + 1
      console.log("current", current)
      const app = getApp()
      app.globalData.lastWordId = thiz.data.wordId
      app.globalData.studiedToday = app.globalData.studiedToday + 1
      console.log("正在更新下一个页面", app.globalData)
      console.log("thisWord,", thiz.data.wordId)
      const batch = wx.getStorageSync('batch')
      if (app.globalData.studiedToday == batch) { //回答最后一个,只有第一次会触发

        wx.cloud.callFunction({
          // 要调用的云函数名称
          name: 'destroy',
          // 传递给云函数的参数
          data: {
            word_id: thiz.data.wordId,
          },
          success: res => {
            // output: res.result === 3
            console.log("today finished")

            thiz.setData({
              wordId: thiz.data.wordId + 1,
            })
          },
        })
        wx.navigateTo({
          url: '/pages/word/end/end',
        })
        return
      }

      //获取下一个的问题
      wx.cloud.callFunction({
        // 要调用的云函数名称
        name: 'getQuestion',
        // 传递给云函数的参数
        data: {
          word_id: (thiz.data.wordId + 1)
        },
        success: res => {
          // output: res.result === 3
          thiz.setData({
            wordId: (thiz.data.wordId + 1),
            word: res.result.word,
            options: res.result.options,
            key: res.result.key,
            question: res.result.question,
            total: total, //总进度
            current: current, //目前进度
            replied: false, //是否回答
            replyIndex: null,
          })
          thiz.setProgress(current, total)
        },
        fail: err => {
          // handle error
        },
        complete: () => {
          // ...
        }
      })
    }, 1000) //1000表示延时1000ms
  },

  /**
   * 点击跳转详情界面
   */
  detail: function(e) {
    if (this.data.wordId == null) {
      wx.showModal({
        title: '错误',
        content: '单词id不存在'
      })
      return
    }
    wx.navigateTo({
      url: '/pages/word/detail/detail?wordId=' + this.data.wordId
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const thiz = this
    console.log("onLoad options", options)
    var wordId = Number(options.wordId)
    var total = Number(options.total)
    var current = Number(options.current)

    this.setData({
      wordId: wordId,
      total: total,
      current: current,
    })


    //获取数据
    this.setWordDataAndOptions(this.data.wordId)

    //设置进度条
    this.setProgress(this.data.current, this.data.total)
  },


  /**
   * 设置进度条
   */
  setProgress(current, total) {
    var number = (current - 1) / total
    var percent = this.toPercent(number) + ""
    console.log("percent", percent)
    this.setData({
      progress: percent
    })
  },

  //获取数据
  setWordDataAndOptions: function(word_id) {
    const thiz = this
    wx.cloud.callFunction({
      // 要调用的云函数名称
      name: 'getQuestion',
      // 传递给云函数的参数
      data: {
        word_id: word_id
      },
      success: res => {
        // output: res.result === 3
        thiz.setData({
          word: res.result.word,
          options: res.result.options,
          question: res.result.question,
          key: res.result.key
        })
      },
      fail: err => {
        // handle error
      },
      complete: () => {
        // ...
      }
    })
  },


  back: function(e) {
    if (this.data.current <= this.data.total) {
      wx.navigateBack({})
      return
    }
    //登陆成功跳转
    var pages = getCurrentPages(); //获取当前页面信息栈
    console.log("pages: ", pages)
    if (pages.length > 1) {
      //上一个页面实例对象
      let i = 0
      for (; i < pages.length; i++) {
        if (pages[i].route == "pages/word/list/list") {
          break
        }
      }
      var targetPage = pages[i]
      console.log("i is", i)
      var options = {}
      options.number = getApp().globalData.studiedToday + 1
      //关键：上一个页面重加载
      targetPage.onLoad(options)
      //返回
      var delta = pages.length - 1 - i
      wx.navigateBack({
        //delta: pages.length
        delta: delta
      })
    }
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    console.log("show")
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    console.log("destroy")
    const thiz = this
    const app = getApp()
    app.globalData.lastWordId = thiz.data.wordId - 1
    wx.cloud.callFunction({
      // 要调用的云函数名称
      name: 'destroy',
      // 传递给云函数的参数
      data: {
        word_id: thiz.data.wordId - 1,
      },
      success: res => {
        // output: res.result === 3
        console.log("success")
      },
      fail: err => {
        // handle error
      },
      complete: () => {
        // ...
      }
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  /**
   * 小数转化为百分数字符串。
   */
  toPercent: function(point) {
    var str = Number(point * 100).toFixed(1);
    str += "%";
    return str;
  },

})